App.controller('busOrderController', ['$rootScope', '$scope', '$state', 'Page', function($rootScope, $scope, $state, Page) {
	
	$scope.orderType = '1';
	
	$scope.counter = 1;
	
	Page.ajaxPostQuiet('customer/list.do', null, function (resp) {
        $scope.customerList = resp.data;
	});
	
    $scope.grid = {
        add : function() {
            $scope.order = {
            	orderType : $scope.orderType
            };
            $scope.modal.setTitle('车身广告上刊制作单');
            $scope.modal.show();
        },
        update: function(row) {
        	$scope.order = row;
    		$($scope.order.orderItems).each(function(idx, _row){
    			_row.rowId = $scope.counter ++;
	    	});
    		$scope.modal.setTitle('车身广告上刊制作单-【' + row.orderId + '】');
            $scope.modal.show();
        },
        save : function() {
        	if(!$scope.validateForm.$valid) {
	            $scope.validateForm.doValidate();
	        } else {
	        	var f = true;
	        	var plateNos = [];
	        	var vehicleNos = [];
	        	$($scope.order.orderItems).each(function(i,oi){
	        		if(!oi.busPlateNo || oi.busPlateNo == '' 
	        			|| !oi.busVehicleNo || oi.busVehicleNo == ''
	        				|| !oi.busCompany || oi.busCompany == ''
	        					|| !oi.busLineName || oi.busLineName == ''
	        						|| !oi.busType || oi.busType == ''){
	        			Page.alert('请填写车辆信息!');
	        			f = false;
	        			return false;
	        		}
	        		
	        		var chongfu = false;
	        		$(plateNos).each(function(i,p){
	        			if(oi.busPlateNo == p){
	        				Page.alert('车牌号重复!');
	        				chongfu = true;
	        				return false;
	        			}
	        		});
	        		if(chongfu){
	        			f = false;
	        			return false;
	        		}else{
	        			plateNos.push(oi.busPlateNo);
	        		}
	        		
	        		$(vehicleNos).each(function(i,v){
	        			if(oi.busVehicleNo == v){
	        				Page.alert('自编号重复!');
	        				chongfu = true;
	        				return false;
	        			}
	        		});
	        		if(chongfu){
	        			f = false;
	        			return false;
	        		}else{
	        			vehicleNos.push(oi.busVehicleNo);
	        		}
	        		
	        		if(oi.data && (oi.bus.plateNo != oi.busPlateNo || oi.bus.vehicleNo != oi.busVehicleNo)){
	        			oi.data = null;
	        			oi.busId = "";
	        		}
	        	});
	        	if(f){
	        		Page.ajaxPost($scope.order.orderId ? 'order/update.do' : 'order/add.do', $scope.order, function() {
		                $scope.grid.query();
		                $scope.grid.cancel();
		            });
	        	}     
	        }
        },
        viewOrder : function(row){
        	$scope.order = row;
    		$scope.viewmodal.setTitle($scope.order.customerName + '车身广告上刊制作单 -【' + row.orderId + '】');
    		$scope.viewmodal.show();
        },
        saveWorkBill : function(order,workbill){
        	if(workbill.workbillItems.length < 1){
        		Page.alert('请选择工作单明细!');
        		return false;
        	}
        	Page.ajaxPost('workBill/add.do', workbill, function() {
        		$scope.workbillsModal.hide();
            });
        },
        column_defs: [
           {
        	  target : 1,
              template: function(row) {
            	  return '<a href="javascript:void(0);" ed-click="viewOrder">' + row.orderId + '</a>';
              }
          },{
            target : 6,
            buttons : [
				{
				    name: '工作单',
				    class: 'btn-warning btm-sm',
				    icon: 'fa-file-word-o',
				    event: function(row){
				    	$scope.order = row;
				    	Page.ajaxPostQuiet('order/workbills/' + row.orderId + '.do', null, function (resp) {
				    		$scope.order.workbills = resp.data;
				    		$($scope.order.workbills).each(function(i,wb){
				    			$(wb.workbillItems).each(function(j,wi){
				    				$($scope.order.orderItems).each(function(k,oi){
						    			if(oi.orderItemId == wi.orderItemId){
						    				if(wb.workbillType == '1'){
						    					oi.stickerWorkbillItem = wi;
						    					oi.stickerWorkbill = wb;
						    				}else if(wb.workbillType == '2'){
						    					oi.publishWorkbillItem = wi;
						    					oi.publishWorkbill = wb;
						    				}
						    				return false;
						    			}
						    		});
					    		});
				    		});
				    		//上刊
				    		$scope.order2 = angular.copy($scope.order);
				    		
				    		//胶贴
				    		$scope.workbill = {
				    			orderId : row.orderId,
				    			workbillType : '1',
				    			workbillItems : []
				    		};
				    		//上刊
				    		$scope.workbill2 = {
					    			orderId : row.orderId,
					    			workbillType : '2',
					    			workbillItems : []
					    		};
				    		$scope.workbillsModal.show();
				    	});
				    }
				},
                {
                    name: '编辑',
                    class: 'btn-warning btm-sm',
                    icon: 'fa-edit',
                    visiable: function(row) {
                        return row.status && row.status == '0';
                    },
                    event: 'update'
                },
                {
                    name: '删除',
                    class: 'btn-danger',
                    icon: 'fa-close',
                    visiable: function(row) {
                        return row.status && row.status == '0';
                    },
                    event: function(row) {
                        Page.confirm("确定要删除吗？", function() {
                            Page.ajaxPost('order/delete.do', row, function() {
                                $scope.grid.query();
                            });
                        });
                    }
                }
            ]
        }]
    };
    
    
    $scope.selectBus = function(orderItem, data){
    	orderItem.bus = data;
    	orderItem.busId = data.busId;
    	orderItem.busPlateNo = data.plateNo;
    	orderItem.busVehicleNo = data.vehicleNo;
    	orderItem.busLineName = data.lineNo;
    	orderItem.busCompany = data.companyName;
    	orderItem.busType = data.busType || orderItem.busType;
    	
    };
    
    $scope.addOrderItemRow = function(){
    	$scope.order.orderItems = $scope.order.orderItems || [];
    	var last = $scope.order.orderItems.length > 0 ? $scope.order.orderItems[$scope.order.orderItems.length - 1] : {};
    	$scope.order.orderItems.push({
    		rowId : $scope.counter ++,
    		busId : '',
    		busPlateNo : '',
    		busVehicleNo : '',
    		busLineName : last.busLineName,
    		busCompany : last.busCompany,
    		busType : '',
    		adName : last.adName,
    		publishType : last.publishType,
    		publishDate : last.publishDate,
    		publishCycle : last.publishCycle
    	});
    };

    $scope.removeOrderItemRow = function(row){
    	if(row.orderItemId && row.orderItemId != ''){
    		Page.confirm('确认删除当前记录?',function(){
    			Page.ajaxPostQuiet('order/item/delete.do', {orderItemId : row.orderItemId}, function (resp) {
    				$($scope.order.orderItems).each(function(idx, _row){
    		    		if(row.rowId && row.rowId == _row.rowId){
    		    			$scope.order.orderItems.splice(idx,1);
    		    			return false;
    		    		}
    		    	});
        		});
    		});
    	}else{
    		$($scope.order.orderItems).each(function(idx, _row){
        		if(row.rowId && row.rowId == _row.rowId){
        			$scope.order.orderItems.splice(idx,1);
        			return false;
        		}
        	});
    	}
    };
    
    $scope.selectWorkBillItem = function(order,workbill,orderItem){
    	var last = workbill.workbillItems.length > 0 ? workbill.workbillItems[workbill.workbillItems.length - 1] : {};
    	orderItem.adId = orderItem.adId || last.adId;
    	orderItem.sampleName = orderItem.sampleName || last.sampleName;
    	orderItem.stickerType = orderItem.stickerType || last.stickerType;
    	orderItem.limitDate = orderItem.limitDate || last.limitDate;
    	workbill.workbillItems = [];
    	$(order.orderItems).each(function(idx, _row){
    		if(_row._selected){
    			workbill.workbillItems.push(_row);
    		}
    	});
    };
    
    $scope.toSelectWorkbillAd = function(order,workbill,orderItem){
    	$scope.orderItem = orderItem;
    	Page.ajaxPostQuiet('adDesign/list/' + $scope.order.customerId + '.do', null, function (resp) {
    		$scope.ads = resp.data;
    		$scope.selectWorkbillAdModal.show();
    	});
    };
    
    $scope.selectWorkbillAd = function(ad){
    	$scope.orderItem.adId = ad.adId;
    	$scope.orderItem.sampleName = '【' + ad.adId + '】-' + ad.adName;
    	$scope.selectWorkbillAdModal.hide();
    };
}]);

App.directive('edTypeaheadExtend', ['$rootScope','Page', function ($rootScope, Page) {
    return {
        restrict: 'A',
        scope: {
        	model : '@ngModel',
            edClick : '&'
        },
        require: 'ngModel',
        controller: ['$scope', '$element', '$rootScope', function($scope, $element, $rootScope){
        	var a = $($element).val();
        	var b = 1;
        }],
        link: function (scope, elem, attrs,ngModelController) {
            var typeahead = $(elem);
            var a = $(elem).val();
            typeahead.attr('id', 'typeahead' + Metronic.getUniqueID());
            var option = AppUtil.jsonfy(attrs.options);
            typeahead.typeahead({
                hint: true,
                highlight: true,
                minLength: 1
            }, {
                displayKey: option.key,
                source: function (query, process) {
                    var params = {'_pageSize': option.count || 5};
                    params[option.key] = query;
                    Page.ajaxPostQuiet(option.url, params, function(result) {
                        var datas = result.data;
                        if (!angular.isArray(datas) && angular.isArray(datas.rows)) {
                            datas = datas.rows;
                        }
                        process(datas);
                    })
                },
                templates: {
                    empty: [
                        '<div class="think-no">',
                        '没有找到相关数据',
                        '</div>'
                    ].join('\n'),
                    suggestion: Handlebars.compile('<div class="think-message">{{'+option.key+'}}</div>')
                }
            }).bind('typeahead:selected', function(obj, data) {// 选中监听;
                if (typeof scope.edClick == 'function') {
                	scope.$apply(function () {
                		scope.edClick({data: data});
        	         });
                }
            });
            
            $(typeahead).unbind('blur');
            
            ngModelController.$render = function() {
                if (typeahead.val() != ngModelController.$viewValue) {
                    typeahead.val(ngModelController.$viewValue);
                }
            };
        }
    };
}]);
